package JPetStore.persistence.impl;

import JPetStore.domain.LineItem;
import JPetStore.persistence.DBUtil;
import JPetStore.persistence.ItemDao;
import JPetStore.persistence.LineItemDao;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class LineItemDaoImpl implements LineItemDao {
    private static final String getLineItemsByOrderIdString = "SELECT ORDERID,LINENUM AS lineNumber,ITEMID,QUANTITY,UNITPRICE FROM LINEITEM WHERE ORDERID = ?";
    private static final String insertLineItemString = "INSERT INTO LINEITEM (ORDERID, LINENUM, ITEMID, QUANTITY, UNITPRICE) VALUES (?, ?, ?, ?,?)";

    public LineItemDaoImpl() {
    }

    public List<LineItem> getLineItemsByOrderId(int orderId) {
        List<LineItem> lineItemList = new ArrayList();

        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement pStatement = connection.prepareStatement(getLineItemsByOrderIdString);
            pStatement.setInt(1,orderId);
            ResultSet resultSet = pStatement.executeQuery();

            while(resultSet.next()) {
                LineItem lineItem = new LineItem();
                lineItem.setOrderId(resultSet.getInt(1));
                lineItem.setLineNumber(resultSet.getInt(2));
                lineItem.setItemId(resultSet.getString(3));
                lineItem.setQuantity(resultSet.getInt(4));
                lineItem.setUnitPrice(resultSet.getBigDecimal(5));
                ItemDao itemDao = new ItemDaoImpl();
                lineItem.setItem(itemDao.getItem(lineItem.getItemId()));
                lineItem.setTotal(lineItem.getUnitPrice().multiply (BigDecimal.valueOf(lineItem.getQuantity())));
                lineItemList.add(lineItem);
            }

            DBUtil.closeResultSet(resultSet);
            DBUtil.closePreparedStatement(pStatement);
            DBUtil.closeConnection(connection);
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        return lineItemList;
    }

    public void insertLineItem(LineItem lineItem) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement pStatement = connection.prepareStatement(insertLineItemString);
            pStatement.setInt(1, lineItem.getOrderId());
            pStatement.setInt(2, lineItem.getLineNumber());
            pStatement.setString(3, lineItem.getItemId());
            pStatement.setInt(4, lineItem.getQuantity());
            pStatement.setBigDecimal(5, lineItem.getUnitPrice());
            pStatement.executeUpdate();
            DBUtil.closePreparedStatement(pStatement);
            DBUtil.closeConnection(connection);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

    }
}
